<template>
	<view class="container">
		<!-- 顶部统计卡片 -->
		<view class="stats-card">
			<!-- 标题和统计信息 -->
			<view class="header-section">
				<text class="title">{{currentSubject}}作业上传</text>
				<text class="subtitle">共{{studentList.length}}名学生 | 已选{{selectedStudents.length}}名</text>
			</view>

			<!-- 学科选择 -->
			<view class="subject-section">
				<view class="section-title">当前科目</view>
				<picker mode="selector" :range="subjects" :value="subjectIndex" @change="changeSubject">
					<view class="subject-picker">
						<text>{{currentSubject || '请选择学科'}}</text>
						<uni-icons type="arrowdown" size="18" color="#666"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 主题选择 -->
			<view class="theme-section">
				<view class="section-title">选择主题</view>
				<view class="theme-container">
					<scroll-view scroll-x class="theme-scroll" scroll-with-animation>
						<view class="theme-list">
							<view v-for="(theme, index) in themes" :key="index" class="theme-item"
								:class="{active: currentTheme === theme}" @click="selectTheme(theme)">
								{{theme}}
							</view>
						</view>
					</scroll-view>
					<view class="add-theme" @click="showAddThemeDialog">
						<uni-icons type="plus" size="20" color="#4a6cf7"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 学生卡片列表 -->
		<view class="student-list">
			<view v-for="(student, index) in studentList" :key="student.userId" class="student-card"
				:class="{'selected': selectedStudents.includes(student.userId)}" @click="toggleStudent(student.userId)">
				<!-- 上传进度背景层 -->
				<view class="progress-bg" :style="{height: uploadProgress[student.userId] + '%'}"></view>

				<view class="card-content">
					<view class="avatar-wrapper">
						<image :src="student.aver || '/static/aver1.jpg'" class="avatar"></image>
						<view v-if="selectedStudents.includes(student.userId)" class="order-badge">
							{{selectedStudents.indexOf(student.userId) + 1}}
						</view>
					</view>
					<view class="student-info">
						<text class="text-bold">{{student.studentName}}</text>
						<!-- 上传状态显示 -->
						<view class="upload-status">
							<text v-if="uploadStatus[student.userId] === 'uploading'" class="status-text">
								{{uploadProgress[student.userId]}}%
							</text>
							<text v-if="uploadStatus[student.userId] === 'success'" class="status-success">
								<uni-icons type="checkmarkempty" size="16" color="#4CAF50"></uni-icons> 已完成
							</text>
							<text v-if="uploadStatus[student.userId] === 'error'" class="status-error">
								<uni-icons type="closeempty" size="16" color="#F44336"></uni-icons> 失败
							</text>
						</view>
					</view>
					<!-- 照片预览区域 -->
					<view v-if="selectedPhotos[index]" class="photo-preview">
						<image :src="selectedPhotos[index].tempFilePath" class="preview-image" mode="aspectFill"
							@click.stop="previewPhoto(selectedPhotos[index].tempFilePath)"></image>
						<view class="remove-photo" @click.stop="removePhoto(index)">×</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作区域 -->
		<view class="fixed-bottom">
			<button class="select-photos-btn" @click="selectPhotos" :disabled="selectedStudents.length === 0">
				选择照片 ({{getSelectedPhotoCount()}}/{{selectedStudents.length}})
			</button>
			<button class="upload-btn" @click="handleUpload" :disabled="getSelectedPhotoCount() === 0">
				批量上传作业
			</button>
		</view>

		<!-- 添加主题对话框 -->
		<uni-popup ref="themeDialog" type="dialog">
			<uni-popup-dialog mode="input" title="添加新主题" placeholder="请输入主题名称"
				@confirm="addNewTheme"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>
<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				grade: '',
				studentList: [],
				selectedStudents: [], // 存储被选中的学生ID
				selectedPhotos: [], // 存储选择的照片
				teacher: {},
				subjects: [], // 学科列表
				currentSubject: '', // 当前选中学科
				subjectIndex: 0, // 当前选中学科索引
				newSubject: '', // 新学科名称
				themes: ['课堂作业', '课后练习', '单元测试', '假期作业'], // 默认主题列表
				currentTheme: '课堂作业', // 当前选中主题
				uploadProgress: {}, // 改为对象形式，存储每个学生的上传进度
				uploadStatus: {}, // 存储每个学生的上传状态
				uploadTasks: [] // 存储上传任务
			}
		},
		onLoad(option) {
			uni.getStorage({
				key: "teacher",
				success: (res) => {
					this.teacher = res.data;
					this.grade = option.grade;
					this.fetchSubjects();
				}
			});
		},
		methods: {
			// 获取学科列表
			fetchSubjects() {
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: `${globalVariable}/getTeacherSubject?grade=${this.grade}&teacherId=${this.teacher.teacherId}`,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							this.subjects = res.data.data.map(item => item.subject);
							if (this.subjects.length > 0) {
								this.currentSubject = this.subjects[0];
								this.fetchStudents();
							}
						} else {
							uni.showToast({
								title: res.data.message || '获取学科失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},

			// 切换学科
			changeSubject(e) {
				this.subjectIndex = e.detail.value;
				this.currentSubject = this.subjects[this.subjectIndex];
				this.fetchStudents();
			},



			// 选择主题
			selectTheme(theme) {
				this.currentTheme = theme;
			},

			// 显示添加主题对话框
			showAddThemeDialog() {
				this.$refs.themeDialog.open();
			},

			// 添加新主题
			addNewTheme(themeName) {
				if (themeName && !this.themes.includes(themeName)) {
					this.themes.unshift(themeName);
					this.currentTheme = themeName;
				}
				this.$refs.themeDialog.close();
			},

			// 显示学科管理对话框
			showSubjectDialog() {
				this.newSubject = '';
				this.$refs.subjectDialog.open();
				this.isSubjectDialogOpen = true;
			},

			// 关闭学科管理对话框
			closeSubjectDialog() {
				this.isSubjectDialogOpen = false;
			},

			// 处理学科操作（添加）
			handleSubjectAction(value) {
				if (value && !this.subjects.includes(value)) {
					this.addSubject(value);
				}
			},

			// 添加学科
			addSubject(subject) {
				uni.showLoading({
					title: '添加中...'
				});
				uni.request({
					url: `${globalVariable}/addTeacherSubject`,
					method: 'POST',
					data: {
						grade: this.grade,
						teacherId: this.teacher.teacherId,
						subject: subject
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							this.subjects.push(subject);
							uni.showToast({
								title: '添加成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.data.message || '添加失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},

			// 删除学科
			removeSubject(index) {
				const subject = this.subjects[index];
				uni.showModal({
					title: '提示',
					content: `确定要删除学科"${subject}"吗?`,
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中...'
							});
							uni.request({
								url: `${globalVariable}/deleteTeacherSubject`,
								method: 'POST',
								data: {
									grade: this.grade,
									teacherId: this.teacher.teacherId,
									subject: subject
								},
								success: (res) => {
									uni.hideLoading();
									if (res.data.status === 1) {
										this.subjects.splice(index, 1);
										if (this.currentSubject === subject) {
											this.currentSubject = this.subjects.length > 0 ? this
												.subjects[0] : '';
											this.subjectIndex = 0;
										}
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										});
									} else {
										uni.showToast({
											title: res.data.message || '删除失败',
											icon: 'none'
										});
									}
								},
								fail: () => {
									uni.hideLoading();
									uni.showToast({
										title: '网络错误',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},
			// 选择照片
			selectPhotos() {
				// 只计算当前已选学生中还没有照片的数量
				const needPhotoCount = this.selectedStudents.length -
					this.selectedStudents.filter(userId => {
						const index = this.studentList.findIndex(s => s.userId === userId);
						return index !== -1 && this.selectedPhotos[index] !== null;
					}).length;

				if (needPhotoCount <= 0) {
					uni.showToast({
						title: '当前已选学生都有照片',
						icon: 'none'
					});
					return;
				}

				uni.chooseImage({
					count: needPhotoCount,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						// 按照点击顺序分配照片
						let photoAssigned = 0;
						const newPhotos = [...this.selectedPhotos];

						// 遍历已选学生(按点击顺序)
						this.selectedStudents.forEach(userId => {
							// 如果已经分配完所有照片则停止
							if (photoAssigned >= res.tempFilePaths.length) return;

							// 找到该学生在完整列表中的位置
							const studentIndex = this.studentList.findIndex(s => s.userId === userId);
							// 只给没有照片的学生分配
							if (studentIndex !== -1 && newPhotos[studentIndex] === null) {
								// 分配照片
								newPhotos[studentIndex] = {
									tempFilePath: res.tempFilePaths[photoAssigned],
									studentId: userId
								};
								photoAssigned++;
							}
						});

						this.selectedPhotos = newPhotos;
					}
				});
			},

			// 获取当前已选学生中已分配照片的数量
			getSelectedPhotoCount() {
				return this.selectedStudents.filter(userId => {
					const index = this.studentList.findIndex(s => s.userId === userId);
					return index !== -1 && this.selectedPhotos[index] !== null;
				}).length;
			},
			// 实际上传照片
			uploadPhotos() {
				const uploadTasks = [];
				this.uploadProgress = 0;

				// 只上传当前已选学生的照片
				const validPhotos = this.selectedStudents.map(userId => {
					const index = this.studentList.findIndex(s => s.userId === userId);
					return index !== -1 ? this.selectedPhotos[index] : null;
				}).filter(photo => photo !== null);

				if (validPhotos.length === 0) {
					uni.showToast({
						title: '没有可上传的照片',
						icon: 'none'
					});
					return;
				}

				// 显示上传进度
				uni.showLoading({
					title: `上传中 0/${validPhotos.length}`,
					mask: true
				});

				validPhotos.forEach((photo, index) => {
					const student = this.studentList.find(s => s.userId === photo.studentId);
					if (!student) return;
					const home = {
						studentId: student.userId,
						studentName: student.studentName,
						grade: student.grade,
						hwType: this.currentSubject, // 学科
						hwEvent: this.currentTheme, // 主题
						teacherId: this.teacher.teacherId,
						teacherName: this.teacher.name
					}
					const task = uni.uploadFile({
						url: `${globalVariable}/uploadHomeWork`,
						filePath: photo.tempFilePath,
						name: 'file',
						formData: {
							homeWork: JSON.stringify(home)
						},
						success: (res) => {
							const data = JSON.parse(res.data);
							if (data.status !== 1) {
								console.error(`上传失败: ${student.studentName}`);
							}
						},
						fail: (err) => {
							console.error(`上传失败: ${student.studentName}`, err);
						},
						complete: () => {
							this.uploadProgress++;
							uni.hideLoading();
							uni.showLoading({
								title: `上传中 ${this.uploadProgress}/${validPhotos.length}`,
								mask: true
							});

							if (this.uploadProgress === validPhotos.length) {
								uni.hideLoading();
								uni.showToast({
									title: '上传完成',
									icon: 'success'
								});
								// 只清除已上传学生的照片，不清除全部
								const newPhotos = [...this.selectedPhotos];
								this.selectedStudents.forEach(userId => {
									const index = this.studentList.findIndex(s => s.userId ===
										userId);
									if (index !== -1) {
										newPhotos[index] = null;
									}
								});
								this.selectedPhotos = newPhotos;
								this.selectedStudents = [];
							}
						}
					});

					uploadTasks.push(task);
				});
			},
			fetchStudents() {
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: `${globalVariable}/getStudentsByGrade?grade=${this.grade}`,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status == 1) {
							this.studentList = res.data.data.map(item => {
								return {
									...item,
									avatar: item.avatar || '/static/default-avatar.png'
								}
							});
							// 初始化照片数组
							this.selectedPhotos = new Array(this.studentList.length).fill(null);
						} else {
							uni.showToast({
								title: '加载失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});
			},
			// 切换学生选择状态
			toggleStudent(userId) {
				if (this.selectedStudents.includes(userId)) {
					// 取消选择时，只从selectedStudents中移除，不删除照片数据
					const index = this.selectedStudents.indexOf(userId);
					this.selectedStudents.splice(index, 1);
				} else {
					// 添加到已选学生列表
					this.selectedStudents.push(userId);
				}
			},

			// 预览照片
			previewPhoto(tempFilePath) {
				uni.previewImage({
					urls: [tempFilePath],
					current: 0
				});
			},
			// 移除照片
			removePhoto(index) {
				// 创建新数组避免直接修改
				const newPhotos = [...this.selectedPhotos];
				newPhotos[index] = null;
				this.selectedPhotos = newPhotos;

				// 如果该学生处于选中状态，则取消选中
				const userId = this.studentList[index].userId;
				if (this.selectedStudents.includes(userId)) {
					const selectedIndex = this.selectedStudents.indexOf(userId);
					this.selectedStudents.splice(selectedIndex, 1);
				}
			},

			// 批量上传
			handleUpload() {
				const photoCount = this.getSelectedPhotoCount();
				if (photoCount === 0) {
					uni.showToast({
						title: '请先选择照片',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '提示',
					content: `确定要上传${photoCount}份作业吗？`,
					success: (res) => {
						if (res.confirm) {
							this.uploadPhotos();
						}
					}
				});
			},

		}
	}
</script>
<style lang="scss" scoped>
	.subject-selector {
		margin: 20rpx 0;
		display: flex;
		justify-content: center;
	}

	.subject-picker {
		padding: 12rpx 30rpx;
		background: rgba(255, 255, 255, 0.7);
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.theme-selector {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		padding: 10rpx 0;
	}

	.theme-scroll {
		flex: 1;
		white-space: nowrap;
		height: 80rpx;
	}

	.theme-item {
		display: inline-flex;
		padding: 10rpx 24rpx;
		margin-right: 16rpx;
		background: rgba(255, 255, 255, 0.6);
		border-radius: 40rpx;
		font-size: 26rpx;
		color: #666;
		border: 1rpx solid rgba(0, 0, 0, 0.1);

		&.active {
			background: #4a6cf7;
			color: white;
			font-weight: bold;
		}
	}

	/* 原有样式保持不变，新增以下样式 */

	.theme-selector {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		padding: 10rpx 0;
	}

	.theme-scroll {
		flex: 1;
		white-space: nowrap;
		height: 80rpx;
	}

	.theme-item {
		display: inline-flex;
		padding: 10rpx 24rpx;
		margin-right: 16rpx;
		background: rgba(255, 255, 255, 0.6);
		border-radius: 40rpx;
		font-size: 26rpx;
		color: #666;
		border: 1rpx solid rgba(0, 0, 0, 0.1);

		&.active {
			background: #4a6cf7;
			color: white;
			font-weight: bold;
		}
	}

	.subject-selector {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.subject-picker {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		background: rgba(255, 255, 255, 0.7);
		display: flex;
		align-items: center;
		font-size: 26rpx;
	}

	.manage-subject-btn {
		background: rgba(255, 255, 255, 0.7);
		color: #666;
		border: none;
		line-height: 1.5;
	}

	.subject-list {
		max-height: 300rpx;
		overflow-y: auto;
		margin-top: 20rpx;
	}

	.subject-item {
		padding: 15rpx;
		border-bottom: 1rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.container {
		padding: 30rpx;
		min-height: 100vh;
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 79, 10, 0.1) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(38, 10, 255, 0.1) 0%, transparent 20%);
	}

	.stats-card {
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
		transition: all 0.2s ease;

		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(233, 92, 246, 0.2) 100%);
			z-index: -1;
		}
	}

	.student-list {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		margin-bottom: 160rpx;
	}

	.student-card {
		background: rgba(255, 255, 255, 0.25);
		backdrop-filter: blur(10px);
		-webkit-backdrop-filter: blur(10px);
		border-radius: 20rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		position: relative;

		&.selected {
			background: rgba(100, 149, 237, 0.3);
			transform: scale(0.98);
		}

		.card-content {
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		.avatar-wrapper {
			position: relative;
			width: 120rpx;
			height: 120rpx;
			margin-bottom: 10rpx;

			.avatar {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				object-fit: cover;
				border: 2rpx solid rgba(255, 255, 255, 0.5);
			}

			.order-badge {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				width: 40rpx;
				height: 40rpx;
				background: #ff6b6b;
				color: white;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				font-weight: bold;
			}
		}

		.student-info {
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;
			margin-bottom: 10rpx;

			.text-bold {
				margin-bottom: 5rpx;
			}
		}

		.photo-preview {
			position: relative;
			width: 100%;
			height: 120rpx;
			margin-top: 10rpx;
			border-radius: 12rpx;
			overflow: hidden;
			border: 1rpx dashed rgba(0, 0, 0, 0.1);

			.preview-image {
				width: 100%;
				height: 100%;
			}

			.remove-photo {
				position: absolute;
				top: 0;
				right: 0;
				width: 40rpx;
				height: 40rpx;
				background: rgba(0, 0, 0, 0.5);
				color: white;
				border-radius: 0 0 0 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
			}
		}
	}

	.fixed-bottom {
		position: fixed;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		display: flex;
		justify-content: space-between;

		button {
			flex: 1;
			margin: 0 10rpx;
			border-radius: 50rpx;
			font-size: 28rpx;
			transition: all 0.3s ease;

			&[disabled] {
				background: #cccccc !important;
				box-shadow: none !important;
				color: #999999 !important;
				opacity: 0.7;
			}
		}

		.select-photos-btn {
			background: linear-gradient(135deg, #6e8efb 0%, #4a6cf7 100%);
			color: white;
			box-shadow: 0 8rpx 20rpx rgba(74, 108, 247, 0.3);
		}

		.upload-btn {
			background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
			color: white;
			box-shadow: 0 8rpx 20rpx rgba(46, 125, 50, 0.3);
		}
	}

	.flex-between {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.text-lg {
		font-size: 36rpx;
	}

	.text-sm {
		font-size: 24rpx;
	}

	.text-bold {
		font-weight: bold;
	}

	.text-gray {
		color: #888;
	}

	.margin-top-xs {
		margin-top: 10rpx;
	}

	.stats-card {
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(20px);
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(255, 255, 255, 0.4);
	}

	.header-section {
		margin-bottom: 30rpx;

		.title {
			display: block;
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}

		.subtitle {
			display: block;
			font-size: 24rpx;
			color: #888;
		}
	}

	.subject-section {
		margin-bottom: 30rpx;

		.section-title {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 16rpx;
		}

		.subject-picker {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			background: rgba(255, 255, 255, 0.8);
			border-radius: 50rpx;
			border: 1px solid rgba(0, 0, 0, 0.1);
			font-size: 28rpx;
			color: #333;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		}
	}

	.theme-section {
		.section-title {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 16rpx;
		}

		.theme-container {
			display: flex;
			align-items: center;
		}

		.theme-scroll {
			width: 80%;
			flex: 1;
			white-space: nowrap;
			height: 80rpx;
		}

		.theme-list {
			display: inline-flex;
			height: 100%;
		}

		.theme-item {
			display: inline-flex;
			align-items: center;
			padding: 0 30rpx;
			margin-right: 20rpx;
			height: 70rpx;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 40rpx;
			font-size: 26rpx;
			color: #666;
			border: 1px solid rgba(0, 0, 0, 0.1);
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			&.active {
				background: #4a6cf7;
				color: white;
				font-weight: bold;
			}
		}

		.add-theme {
			width: 70rpx;
			height: 70rpx;
			margin-left: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 50%;
			border: 1px dashed #4a6cf7;
		}
	}
</style>